package com.isyscore.os.metadata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.base.Strings;
import com.isyscore.os.core.exception.DataFactoryException;
import com.isyscore.os.core.exception.ErrorCode;
import com.isyscore.os.metadata.common.CommonService;
import com.isyscore.os.metadata.dao.SqlStatementMapper;
import com.isyscore.os.metadata.model.entity.SqlStatement;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.isyscore.os.core.exception.ErrorCode.DATA_NOT_FOUND;
import static java.util.Collections.emptyList;

/**
 * <p>
 * 存储数据模型和数据指标对应的SQL语句 服务实现类
 * </p>
 *
 * @author
 * @since 2021-08-11
 */
@Service
public class SqlStatementService extends CommonService<SqlStatementMapper, SqlStatement> {

    public String getSqlById(Long id) {
        SqlStatement sqlStatement = this.getById(id);
        if (sqlStatement != null) {
            return sqlStatement.getEncodedSql();
        } else {
            throw new DataFactoryException(DATA_NOT_FOUND, "定义的sql语句");
        }
    }

    public Long saveSql(String sql) {
        if (Strings.isNullOrEmpty(sql)) {
            throw new DataFactoryException(ErrorCode.SQL_FORMAT_ERROR);
        }
        if (sql.endsWith(";")) {
            sql = sql.substring(0, sql.length() - 1);
        }
        SqlStatement sqlStatement = new SqlStatement();
        sqlStatement.setEncodedSql(sql);
        this.save(sqlStatement);
        return sqlStatement.getId();
    }

    public void updateSql(Long sqlId, String newSql) {
        SqlStatement sqlStatement = this.getById(sqlId);
        sqlStatement.setEncodedSql(newSql);
        this.updateById(sqlStatement);
    }

    public void importData(List<SqlStatement> sqlStatements) {
        if (sqlStatements.isEmpty()) {
            return;
        }
        Set<Long> ids = sqlStatements.stream().map(SqlStatement::getId).collect(Collectors.toSet());
        LambdaQueryWrapper<SqlStatement> qw = new LambdaQueryWrapper<SqlStatement>();
        qw.in(SqlStatement::getId, ids);
        this.remove(qw);
        this.saveBatch(sqlStatements);
    }

    public List<SqlStatement> getDataByIds(Set<Long> ids) {
        if (ids.isEmpty()) {
            return emptyList();
        }
        LambdaQueryWrapper<SqlStatement> qw = new LambdaQueryWrapper<SqlStatement>();
        qw.in(SqlStatement::getId, ids);
        return this.list(qw);
    }

}
